package com.zhoug.zmui3.input;

import android.content.Context;
import android.content.res.TypedArray;
import android.graphics.Typeface;
import android.graphics.drawable.Drawable;
import android.text.Editable;
import android.text.InputFilter;
import android.text.InputType;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.text.method.DigitsKeyListener;
import android.util.AttributeSet;
import android.view.Gravity;
import android.view.View;
import android.view.ViewGroup;
import android.widget.EditText;
import android.widget.TextView;

import com.zhoug.common3.filters.PhoneFormat;
import com.zhoug.common3.interfaces.TextChangedListener;
import com.zhoug.common3.utils.LogUtils;
import com.zhoug.common3.utils.ZOptional;
import com.zhoug.zmui3.R;

import androidx.annotation.AttrRes;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.appcompat.widget.AppCompatTextView;

/**
 * 键值对文本框
 *
 * @Author: zhoug
 * @Date: 2024-07-08
 * @Description:
 */
public class ZMUIInputTextView extends ZMUIInputView {
    protected TextView mValueView;
    /**
     * 输入电话号码 格式 xxx xxxx xxx
     */
    protected boolean mIsPhone334;
    protected boolean mIfPhone334;
    private Phone334TextWatcher mPhone334TextWatcher;


    public ZMUIInputTextView(Context context) {
        this(context, null);
    }

    public ZMUIInputTextView(Context context, @Nullable AttributeSet attrs) {
        this(context, attrs, R.attr.zmui_style_ZMUIInputTextView);
    }

    public ZMUIInputTextView(Context context, @Nullable AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
        init(context, attrs, defStyleAttr);
    }

    private void init(@NonNull Context context, @Nullable AttributeSet attrs, @AttrRes int defStyleAttr) {
        TypedArray a = context.getTheme().obtainStyledAttributes(attrs, R.styleable.ZMUIInputTextView, defStyleAttr, R.style.zmui_style_ZMUIInputTextView);
        String value = a.getString(R.styleable.ZMUIInputTextView_zmui_value);
        String valueHint = a.getString(R.styleable.ZMUIInputTextView_zmui_valueHint);
        float valueSize = a.getDimension(R.styleable.ZMUIInputTextView_zmui_valueSize, 0);
        int valueColor = a.getColor(R.styleable.ZMUIInputTextView_zmui_valueColor, 0);
        int valueHintColor = a.getColor(R.styleable.ZMUIInputTextView_zmui_valueHintColor, 0);
        int valueStyle = a.getInt(R.styleable.ZMUIInputTextView_zmui_valueStyle, Typeface.NORMAL);
        int valueGravity = a.getInt(R.styleable.ZMUIInputTextView_zmui_valueGravity, Gravity.CENTER_VERTICAL | Gravity.START);
        int valueMaxLines = a.getInt(R.styleable.ZMUIInputTextView_zmui_valueMaxLines, 0);
        int inputType = a.getInt(R.styleable.ZMUIInputTextView_android_inputType, InputType.TYPE_NULL);
        String digits = a.getString(R.styleable.ZMUIInputTextView_android_digits);
        mIsPhone334 = a.getBoolean(R.styleable.ZMUIInputTextView_zmui_isPhone334, false);
        mIfPhone334 = a.getBoolean(R.styleable.ZMUIInputTextView_zmui_ifPhone334, false);
        int valueMaxEms = a.getInt(R.styleable.ZMUIInputTextView_zmui_valueMaxEms, 0);
        int valueMaxLength = a.getInt(R.styleable.ZMUIInputTextView_zmui_valueMaxLength, 0);
        Drawable textCursorDrawable=a.getDrawable(R.styleable.ZMUIInputTextView_android_textCursorDrawable);

        a.recycle();

        TextView valueView = getValueView();
        valueView.setText(value);
        valueView.setHint(valueHint);
        setTextSize(valueView, valueSize);
        setTextColor(valueView, valueColor);
        setTypeface(valueView, valueStyle);
        setHintTextColor(valueView, valueHintColor);
        valueView.setGravity(valueGravity);
        valueView.setEllipsize(TextUtils.TruncateAt.END);
        if (valueMaxLines > 0) {
            valueView.setMaxLines(valueMaxLines);
            if (valueMaxLines == 1) {
                valueView.setSingleLine(true);
            }
        }

        if (valueView instanceof EditText editText) {
            if (inputType != InputType.TYPE_NULL) {
                editText.setInputType(inputType);
            }
            if (digits != null) {
                editText.setKeyListener(DigitsKeyListener.getInstance(digits));
            }
        }

        if (mValueHeight > 0 || mValueHeight == ViewGroup.LayoutParams.MATCH_PARENT) {
            //高度固定
            ViewGroup.LayoutParams layoutParams = valueView.getLayoutParams();
            layoutParams.height = ViewGroup.LayoutParams.MATCH_PARENT;
            valueView.setLayoutParams(layoutParams);
        } else {
            if (mValueMinHeight > 0) {
                valueView.setMinHeight(mValueMinHeight);
            }
            if (mValueMaxHeight > 0) {
                valueView.setMaxHeight(mValueMaxHeight);
            }
        }
        if (valueMaxEms > 0) {
            valueView.setMaxEms(valueMaxEms);
        }
        if (valueMaxLength > 0) {
            valueView.setFilters(new InputFilter[]{new InputFilter.LengthFilter(valueMaxLength)});
        }
        if(textCursorDrawable!=null){
            com.zhoug.common3.utils.TextUtils.setTextCursorDrawable(valueView, textCursorDrawable);
        }


        //监听输入改变 显示/隐藏清除图标
        valueView.addTextChangedListener((TextChangedListener) s -> {
            LogUtils.d(TAG, "init:" + (s != null ? s.toString() : "null"));
            if (mClearIconEnable && isEnabled()) {
                Boolean isEmpty = ZOptional.ofNullable(s)
                        .map(Object::toString)
                        .map(String::isEmpty)
                        .orElse(true);
                if (!Boolean.TRUE.equals(isEmpty) && mValueView.isFocused()) {
                    mClearImageView.setVisibility(VISIBLE);
                } else {
                    mClearImageView.setVisibility(GONE);
                }
            }
        });
        setPhone334();
        mValueView.setOnFocusChangeListener(this);
    }


    @Override
    protected View createValueView(ViewGroup parent) {
        if (mValueView == null) {
            mValueView = new AppCompatTextView(getContext());
        }
        return mValueView;
    }


    public void setPhone334(boolean phone334) {
        mIsPhone334=phone334;
        setPhone334();
    }

    public void setIfPhone334(boolean ifPhone334) {
        mIfPhone334=ifPhone334;
        setPhone334();
    }

    protected void setPhone334( ) {
        if (mValueView != null) {
            if (mPhone334TextWatcher != null) {
                mValueView.removeTextChangedListener(mPhone334TextWatcher);
            }
            if (mIsPhone334 || mIfPhone334) {
                if (mPhone334TextWatcher == null) {
                    mPhone334TextWatcher = new Phone334TextWatcher();
                }
                mValueView.addTextChangedListener(mPhone334TextWatcher);
            }
        }
    }


    public TextView getValueView() {
        return mValueView;
    }

    public @Nullable String getValue() {
        if (mValueView != null) {
            CharSequence text = mValueView.getText();
            if (text != null) {
                String s = text.toString();
                if (mIsPhone334|| mIfPhone334) {
                    return PhoneFormat.getPhoneNumber(s);
                }
                return TextUtils.isEmpty(s) ? null : s;
            }
        }
        return null;
    }

    public void setValue(CharSequence value) {
        if (mValueView != null) {
            mValueView.setText(value);
        }
    }

    @Override
    protected void onClearClick(View view) {
        //清除输入
        mValueView.setText(null);
    }


    @Override
    public void setEnabled(boolean enabled) {
        super.setEnabled(enabled);
        if (mValueView != null) {
            mValueView.setEnabled(enabled);
        }
    }

    @Override
    public void clearFocus() {
        super.clearFocus();
        mValueView.clearFocus();
    }

    @Override
    public void onFocusChange(View v, boolean hasFocus) {
        super.onFocusChange(v, hasFocus);
        if (mClearImageView != null) {
            //焦点改变的时候显示/隐藏清除按钮
            CharSequence text = mValueView.getText();
            if (mClearIconEnable && hasFocus && isEnabled() && text != null && !text.toString().isEmpty()) {
                mClearImageView.setVisibility(VISIBLE);
            } else {
                mClearImageView.setVisibility(GONE);
            }
        }
    }


    private class Phone334TextWatcher implements TextWatcher {
        @Override
        public void beforeTextChanged(CharSequence s, int start, int count, int after) {

        }


        @Override
        public void onTextChanged(CharSequence s, int start, int before, int count) {

        }

        @Override
        public void afterTextChanged(Editable s) {
            if (mValueView instanceof EditText) {
                if(mIsPhone334){
                    PhoneFormat.onTextChanged344((EditText) mValueView, s);
                }else if(mIfPhone334){
                    PhoneFormat.afterTextChangedIf334((EditText) mValueView, s);
                }
            }
        }
    }

}
